package cn.cs.util;


import cn.cs.util.http.HttpClientConnectionManager;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.*;


public class GetWxOrderno
{
  public static DefaultHttpClient httpclient;

  static
  {
    httpclient = new DefaultHttpClient();
    httpclient = (DefaultHttpClient) HttpClientConnectionManager.getSSLInstance(httpclient);
  }
   public GetWxOrderno(){
	   
   }

  /**
   *description:获取预支付id
   *@param url
   *@param xmlParam
   *@return
   * @author ex_yangxiaoyi
   * @see
   */
  public static String getPayNo(String url,String xmlParam){
	  /*DefaultHttpClient client = new DefaultHttpClient();
	  client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
	  HttpPost httpost= HttpClientConnectionManager.getPostMethod(url);
	  String prepay_id = "";
     try {
		 httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
		 HttpResponse response = httpclient.execute(httpost);
	     String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
	    if(jsonStr.indexOf("FAIL")!=-1){
	    	return prepay_id;
	    }
	    Map map = doXMLParse(jsonStr);
	    prepay_id  = (String) map.get("prepay_id");
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return prepay_id;*/
	  System.out.println("xml是:"+xmlParam);
	  DefaultHttpClient client = new DefaultHttpClient();
	  client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
	  HttpPost httpost= HttpClientConnectionManager.getPostMethod(url);
	  String prepay_id = "";
     try {
		 httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
		 HttpResponse response = httpclient.execute(httpost);
	     String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
	     Map<String, Object> dataMap = new HashMap<String, Object>();
	     System.out.println("json是:"+jsonStr);
	     
	    if(jsonStr.indexOf("FAIL")!=-1){
	    	return prepay_id;
	    }
	    Map map = doXMLParse(jsonStr);
	    String return_code  = (String) map.get("return_code");
	    prepay_id  = (String) map.get("prepay_id");
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return prepay_id;
  }
  
  /**
   *description:获取扫码支付连接
   *@param url
   *@param xmlParam
   *@return
   * @author ex_yangxiaoyi
   * @see
   */
  public static String getCodeUrl(String url,String xmlParam){
	  DefaultHttpClient client = new DefaultHttpClient();
	  client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
	  HttpPost httpost= HttpClientConnectionManager.getPostMethod(url);
	  String code_url = "";
     try {
		 httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));
		 HttpResponse response = httpclient.execute(httpost);
	     String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
	    if(jsonStr.indexOf("FAIL")!=-1){
	    	return code_url;
	    }
	    Map map = doXMLParse(jsonStr);
	    code_url  = (String) map.get("code_url");
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return code_url;
  }

	/**
	 * 微信 企业付款（转账给用户） 带证书
	 * @param url
	 * @param xmlParam
	 * @return
	 */
	public static Map<String, Object> sendWxXml(String url,String xmlParam)throws Exception{
		Logger logger = Logger.getLogger(GetWxOrderno.class);
		KeyStore keyStore  = KeyStore.getInstance("PKCS12");

		InputStream inputStream = GetWxOrderno.class.getClassLoader().getResourceAsStream("apiclient_cert.p12");

		//FileInputStream instream = new FileInputStream(new File("cs-pay\\src\\main\\resources\\static\\apiclient_cert.p12"));
		keyStore.load(inputStream, "1528613081".toCharArray());//证书密码
		inputStream.close();
		SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "1528613081".toCharArray()).build();

		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,new String[] { "TLSv1" },null,

				SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

		CloseableHttpClient httpclient = HttpClients.custom() .setSSLSocketFactory(sslsf) .build();
		HttpPost httpost = new HttpPost(url); // 璁剧疆鍝嶅簲澶翠俊鎭?

		httpost.addHeader("Connection", "keep-alive");

		httpost.addHeader("Accept", "*/*");

		httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

		httpost.addHeader("Host", "api.mch.weixin.qq.com");

		httpost.addHeader("X-Requested-With", "XMLHttpRequest");

		httpost.addHeader("Cache-Control", "max-age=0");

		httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");

		httpost.setEntity(new StringEntity(xmlParam, "UTF-8"));

		CloseableHttpResponse response = httpclient.execute(httpost);
		response.setLocale(Locale.SIMPLIFIED_CHINESE);
		logger.info("info ---------------------语言"+response.getLocale());
		HttpEntity entity = response.getEntity();

		InputStream  is =entity.getContent();

		String jsonStrIs = toString(is);
		System.out.println(jsonStrIs);

//		String jsonStr = EntityUtils .toString(response.getEntity(), "UTF-8");

//		logger.info("info---------------------------------------------------------jsonStr：" + new String(jsonStr.getBytes("ISO-8859-1"), "UTF-8"));
//		logger.info("info---------------------------------------------------------jsonStr：" + new String(jsonStr.getBytes("UTF-8"), "ISO-8859-1"));
//		logger.info("info---------------------------------------------------------jsonStr：" + jsonStr);

		logger.info("info---------------------------------------------------------jsonStr：" + new String(jsonStrIs.getBytes("ISO-8859-1"), "UTF-8"));
		logger.info("info---------------------------------------------------------jsonStr：" + new String(jsonStrIs.getBytes("UTF-8"), "ISO-8859-1"));
		logger.info("info---------------------------------------------------------jsonStrIs：" + new String(jsonStrIs.getBytes("ANSI_X3.4-1968"), "UTF-8"));
		logger.info("info---------------------------------------------------------jsonStrIs：" + new String(jsonStrIs.getBytes("UTF-8"), "ANSI_X3.4-1968"));
		logger.info("info---------------------------------------------------------jsonStrIs：" + jsonStrIs);
		System.out.println(jsonStrIs);
		EntityUtils.consume(entity);
		Map<String, Object> map = new HashMap<String, Object>();
//		if(jsonStr.indexOf("FAIL")!=-1){
//			return map;
//		}
		map = doXMLParse(jsonStrIs);

		return map;
	}

	public static String toString(InputStream is) {

		try {
			ByteArrayOutputStream boa=new ByteArrayOutputStream();
			int len=0;
			byte[] buffer=new byte[1024];

			while((len=is.read(buffer))!=-1){
				boa.write(buffer,0,len);
			}
			is.close();
			boa.close();
			byte[] result=boa.toByteArray();

			String temp=new String(result);

//识别编码
			if(temp.contains("utf-8")){
				return new String(result,"utf-8");
			}else if(temp.contains("gb2312")){
				return new String(result,"gb2312");
			}else{
				return new String(result,"utf-8");
			}


		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}

	}

	/**
	 * 创建连接
	 * @param reqUrl 请求地址
	 * @param reqBody 发送内容
	 * @paramNoSuchAlgorithmException
	 */
	public HttpsURLConnection createSSLConnection(String reqUrl, String reqBody) throws Exception{
		URL url = new URL(reqUrl);
		HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
		conn.setConnectTimeout(30000); // 设置连接主机超时（单位：毫秒)
		conn.setReadTimeout(30000); // 设置从主机读取数据超时（单位：毫秒)
		conn.setDoOutput(true); // post请求参数要放在http正文内，顾设置成true，默认是false
		conn.setDoInput(true); // 设置是否从httpUrlConnection读入，默认情况下是true
		conn.setUseCaches(false); // Post 请求不能使用缓存
		// 设定传送的内容类型是可序列化的java对象(如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
		conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		conn.setRequestMethod("POST");// 设定请求的方法为"POST"，默认是GET
		conn.setRequestProperty("Content-Length", reqBody.length() + "");
		//验证主机
		conn.setHostnameVerifier(new HostnameVerifier() {
			@Override
			public boolean verify(String s, SSLSession sslSession) {
				return true;
			}
		});
		try {
			SSLSocketFactory sslSocketFactory = initCert();
			conn.setSSLSocketFactory(sslSocketFactory);
		}catch (Exception e){
			throw new Exception("证书加载错误");
		}
		String encode = "utf-8";
		OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream(), encode);
		out.write(reqBody.toString());
		out.flush();
		out.close();
		return conn;
	}


	public Map<String, Object> sendPost(String url, String param) throws Exception {
		Logger logger = Logger.getLogger(GetWxOrderno.class);
		OutputStreamWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			HttpsURLConnection conn = (HttpsURLConnection)realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			try {
				SSLSocketFactory sslSocketFactory = initCert();
				conn.setSSLSocketFactory(sslSocketFactory);
			}catch (Exception e){
				throw new Exception("证书加载错误");
			}
			// 获取URLConnection对象对应的输出流
			out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
			// 发送请求参数

			out.write(param);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			System.out.println("发送 POST 请求出现异常！" + e);
			e.printStackTrace();
		}
		//使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
		logger.info("info---------------------------------------------------------jsonStrIs：" + result);
		Map<String, Object> map = new HashMap<String, Object>();
		map = doXMLParse(result);

		return map;

	}


	/**
	 * 加载证书
	 */
	private SSLSocketFactory initCert() throws Exception {
		InputStream inputStream = null;
		try {
			inputStream = GetWxOrderno.class.getClassLoader().getResourceAsStream("apiclient_cert.p12");

			//将证书加载进证书库
			KeyStore ks = KeyStore.getInstance("PKCS12");
			ks.load(inputStream, "1528613081".toCharArray());//证书密码
			//初始化秘钥管理器
			KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
			keyManagerFactory.init(ks, "1528613081".toCharArray());

			//信任所有证书
			X509TrustManager tm = new X509TrustManager() {
				@Override
				public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { }

				@Override
				public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { }

				@Override
				public X509Certificate[] getAcceptedIssuers() {
					return null;
				}
			};

			SSLContext sslContext = SSLContext.getInstance("TLS");

			// 第一个参数是授权的密钥管理器，用来授权验证。TrustManager[]第二个是被授权的证书管理器，用来验证服务器端的证书。第三个参数是一个随机数值，可以填写null
			sslContext.init(keyManagerFactory.getKeyManagers(), new TrustManager[]{tm}, null);
			return sslContext.getSocketFactory();
		}catch(Exception e){
			e.printStackTrace();
			throw new Exception(e.getMessage());
		}finally {
			if(inputStream != null){
				try{inputStream.close();}catch (IOException e1){e1.printStackTrace();}
			}
		}
	}


  /**
	 * 解析xml,返回第一级元素键值对。如果第一级元素有子节点，则此节点的值是子节点的xml数据。
	 * @param strxml
	 * @return
	 * @throws IOException
	 */
	public static Map doXMLParse(String strxml) throws Exception {
		if(null == strxml || "".equals(strxml)) {
			return null;
		}
		
		Map m = new HashMap();
		InputStream in = String2Inputstream(strxml);
		SAXBuilder builder = new SAXBuilder();
		Document doc = builder.build(in);
		Element root = doc.getRootElement();
		List list = root.getChildren();
		Iterator it = list.iterator();
		while(it.hasNext()) {
			Element e = (Element) it.next();
			String k = e.getName();
			String v = "";
			List children = e.getChildren();
			if(children.isEmpty()) {
				v = e.getTextNormalize();
			} else {
				v = getChildrenText(children);
			}
			
			m.put(k, v);
		}
		
		//关闭流
		in.close();
		
		return m;
	}
	/**
	 * 获取子结点的xml
	 * @param children
	 * @return String
	 */
	public static String getChildrenText(List children) {
		StringBuffer sb = new StringBuffer();
		if(!children.isEmpty()) {
			Iterator it = children.iterator();
			while(it.hasNext()) {
				Element e = (Element) it.next();
				String name = e.getName();
				String value = e.getTextNormalize();
				List list = e.getChildren();
				sb.append("<" + name + ">");
				if(!list.isEmpty()) {
					sb.append(getChildrenText(list));
				}
				sb.append(value);
				sb.append("</" + name + ">");
			}
		}
		
		return sb.toString();
	}
  public static InputStream String2Inputstream(String str) {
		return new ByteArrayInputStream(str.getBytes());
	}
  
}